﻿using PMS.Core.Configuration.CommonEnumConfigs;
using PMS.Data.Entities.SystemModules;
using PMS.Services.EntityServices.Stores;
using PMS.Services.EntityServices.SystemModules;
using PMS.Web.Models;
using PMS.Web.Models.SystemModules;
using System;
using System.Collections.Generic;
using System.Linq;

namespace PMS.Web.Factories.SystemModules
{
    public class SystemModuleModleFactory : ISystemModuleModleFactory
    {
        #region Fields
        private readonly IStoreMappingService _storeMappingService;
        private readonly ISystemModuleService _systemModuleService;
        #endregion

        #region Ctor
        public SystemModuleModleFactory(IStoreMappingService storeMappingService,
            ISystemModuleService systemModuleService)
        {
            _storeMappingService = storeMappingService;
            _systemModuleService = systemModuleService;
        }
        #endregion

        #region Utils
        protected SystemModuleModel ConvertToModel(SystemModule entity)
        {
            if (entity == null) return null;

            var model = entity.ToModel<SystemModuleModel>();
            if (entity.LimitedToStores)
            {
                var storeIds = _storeMappingService.GetStoresIdsWithAccess(entity).ToList();
                model.LimitedStoreIds = storeIds;
            }

            return model;
        }
        #endregion

        #region Methods
        /// <summary>
        /// WebApi Call For SystemMenu Preparing
        /// </summary>
        /// <param name="storeId"></param>
        /// <param name="customerId"></param>
        /// <param name="loadAll">
        ///    False : 默认false,按用户所有角色权限加载系统菜单 用于后台主页菜单数据加载
        ///    True : 当前Store所有菜单数据加载，用于系统模块编辑页加载父级菜单
        /// </param>
        /// <returns></returns>
        public virtual IList<SystemMenuModel> PrepareSystemMenuModels(int storeId, int customerId, bool loadAll = false)
        {
            var customerModules = loadAll 
                                ? _systemModuleService.GetAllSystemModulesInStore(storeId)
                                : _systemModuleService.GetSysteModulesByCustomer(storeId, customerId);
            if(customerModules?.Any() ?? false)
            {
                var menuModels = customerModules.Select(m => {
                    var model = new SystemMenuModel
                    {
                        Id = m.Id,
                        Title = m.DisplayName,
                        ParentId = m.ParentModuleId,
                        Icon = m.HtmlIconCSSClass,
                        Type = (string.IsNullOrEmpty(m.RouteUrl) && m.OpenMode == LinkOpenMode.None)
                             ? 0  //目录
                             : 1, //菜单
                        OpenType = string.Empty,
                        Href = string.Empty,
                        Order = m.DisplayOrder
                    };
                    if (!string.IsNullOrEmpty(m.RouteUrl))
                    {
                        model.OpenType = m.OpenMode == LinkOpenMode.NewWindow
                                       ? "_blank"
                                       : "_iframe";
                        if (m.RouteUrl.IndexOf("hashid=", StringComparison.InvariantCultureIgnoreCase) < 0)
                            model.Href = m.RouteUrl + (m.RouteUrl.IndexOf('?') > 0 ? "&" : "?") + $"hashid={model.HashId}";
                    }
                    return model;
                }).ToList();
                return menuModels;
            }
            return null;
        }

        /// <summary>
        /// Get All SystemModules For TreeTable List
        /// </summary>
        /// <param name="storeId"></param>
        /// <returns></returns>
        public IList<SystemModuleModel> PrepareAllSystemModuleModels(int storeId)
        {
            var allModules = _systemModuleService.GetAllSystemModulesInStore(storeId);
            if(allModules?.Any() ?? false)
            {
                var moduleModels = allModules.Select(m => ConvertToModel(m)).ToList();
                return moduleModels;
            }
            return null;
        }

        /// <summary>
        /// Get A SystemModule Model
        /// </summary>
        /// <param name="moduleId"></param>
        /// <returns></returns>
        public virtual SystemModuleModel GetSystemModuleModel(int moduleId)
        {
            var entity = _systemModuleService.GetSystemModuleById(moduleId);
            return ConvertToModel(entity);    
        }

        /// <summary>
        /// Get A SystemModuleModel from db by EntityId, return a new Model when EntityNotFound
        /// </summary>
        /// <param name="moduleId"></param>
        /// <returns></returns>
        public virtual SystemModuleModel PrepareSystemModuleModelForEdit(int moduleId)
        {
            var model = GetSystemModuleModel(moduleId);
            if (model == null)
                return (new SystemModule()).ToModel<SystemModuleModel>();
            return model;
        }

        /// <summary>
        /// Get all modulebutton models
        /// </summary>
        /// <returns></returns>
        public virtual IList<ModuleButtonModel> PrepareAllModuleButtons()
        {
            var buttons = _systemModuleService.GetAllModuleButtons();
            return buttons.Select(entity => entity.ToModel<ModuleButtonModel>()).ToList();
        }
        #endregion
    }
}
